//
//  FRMainTopView.m
//  Live
//
//  Created by 徐芙蓉 on 2017/7/26.
//  Copyright © 2017年 Afra. All rights reserved.
//

#import "FRMainTopView.h"

@interface FRMainTopView ()
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) NSMutableArray *buttons;

@end
@implementation FRMainTopView

-(NSMutableArray *)buttons
{
    if (!_buttons) {
        _buttons = [NSMutableArray array];
    }
    return _buttons;
}

- (instancetype)initWithFrame:(CGRect)frame titleNames: (NSArray *)titles
{
    self = [super initWithFrame:frame];
    if (self) {
//        CGFloat btnW = self.frame.size.width /titles.count;
//        CGFloat btnH = self.frame.size.height;
        //使用yykit
        CGFloat btnW = self.width /titles.count;
        CGFloat btnH = self.height;
        for (NSInteger i = 0; i < titles.count; i++) {
            UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [titleBtn setTitle:titles[i] forState:UIControlStateNormal];
            //设置按钮文字
            [titleBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            titleBtn.titleLabel.font = [UIFont systemFontOfSize:18.0];
            titleBtn.frame = CGRectMake(btnW * i, 0, btnW, btnH);
            titleBtn.tag = i;
            [titleBtn addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:titleBtn];
            [self.buttons addObject:titleBtn];
            
            if (i == 1) {
                
//                CGFloat h = 2;
//                CGFloat y =35;
                [titleBtn.titleLabel sizeToFit];
                self.lineView = [[UIView alloc]init];
                self.lineView.backgroundColor = [UIColor whiteColor];
                 [self addSubview:self.lineView];
//                __weak typeof (self) weakSelf = self;
                [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.mas_equalTo(40);
                    make.width.equalTo(titleBtn.titleLabel.mas_width);
                    make.height.mas_equalTo(2);
                    make.centerX.equalTo(titleBtn.mas_centerX);
                }];
               
            }
        }
    }
    return self;
}

-(void)titleClick: (UIButton *)button
{
    self.block(button.tag);
    [self scrolling:button.tag];
}

//mainVC滚动时调用
-(void)scrolling:(NSInteger) tag
{
    UIButton *button = self.buttons[tag];
    
    [UIView animateWithDuration:0.5 animations:^{
        self.lineView.centerX = button.centerX;
    }];
}



@end
